package com.example.homework_03;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;

//选择对话框
public class ChoiceDialog extends DialogFragment {

    private String[] genders = {"男", "女"};
    private ChoiceListener listener;

    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) ;
        builder.setTitle("选择对话框")
                //绑定选框内容,以及绑定回调函数
                .setItems(genders, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //回调函数会返回选择框中的序号，根据序号的得到所选内容传输给Listener
                        //Listener对所选值进行操作
                        listener.onClicked(genders[which]);
                    }
                });
        return builder.create() ;
    }

    ChoiceDialog(ChoiceListener listener) {
        setListener(listener);
    }

    //外部传进来得lisener都要实现处理选择结果得方法
    public interface ChoiceListener {
        public void onClicked(String choice);
    }

    //绑定外部传进来的lisener
    public void setListener(ChoiceListener listener) {
        this.listener = listener;
    }
}
